<template>
  <div id="addNewAppointment">
    <!-- 就诊时间选择 -->
    <div class='mc' v-show='isTime' @click.stop='toggle(0)'></div>
    <div class='datetime' style="z-index: 20;">
      <div class='top'>
        <a @click.stop='toggle(0)'>取消</a>
        <a @click.stop='sureTime'>确定</a>
      </div>
      <mt-picker :slots="slotsTime" @change="onValuesChangeTime"></mt-picker>
    </div>
    <header>
      <span @click="goBack()">返回</span>
      <div>{{status}}</div>
      <span @click='save'>保存</span>
    </header>
    <div class="marks" v-if="showMarks">

      <div class="allTime">
        <div @click.stop='showMarks=false' style="width:97%;
                  height:0.4rem;
                  position: absolute;">
          <i style="background: #000;
                        width:0.15rem;
                        height: 1px;
                        position: absolute;
                        transform: rotate(135deg);
                        top: 0.1rem;
                        right: 0.05rem;"></i>
          <i style="background: #000;
                    transform: rotate(45deg);
                    width:0.15rem;
                    height: 1px;
                    position: absolute;
                    top: 0.1rem;
                    right: 0.05rem;"></i>
        </div>
        <ul class="ltip">
          <el-menu default-active="1" class="el-menu-vertical-demo" @open="handleOpen" @close="handleClose">
            <el-submenu v-for="(item,index) in kindlist" :index="index+''" :key="index">
              <span slot="title" style="letter-spacing:0.01rem;" @click=select1(item.id)>{{item.name}}</span>
              <el-submenu v-for="(item,index) in item.childItems" :index="item.id+''" :key="index">
                <span slot="title" style="letter-spacing: 0.01rem;" @click=select1(item.id)>{{item.name}}</span>
                <el-menu-item index="item.id+''" style="letter-spacing: 0.01rem;" v-for="(item,index) in item.childItems"
                  @click=select1(item.id)>
                  <span slot="title">{{item.name}} </span>
                </el-menu-item>
              </el-submenu>
            </el-submenu>
          </el-menu>
        </ul>
        <div style="background: rgba(64, 158, 255 ,0.5);
                    position: fixed;
                    bottom: 0px;
                    left: 0px;
                    width: 100%;
                    height: 30px;
                    line-height: 30px;
                    border-bottom-right-radius: 8px;
                    border-bottom-left-radius: 8px;
                    text-align: center;"
          @click=sure()>确定</div>
      </div>
    </div>
    <div>
      <ul class="base">
        <li class='noBack'>
          姓名:
          <input type="text" placeholder="请填写患者真实姓名" v-model='obj.name'>
        </li>
        <li class='noBack'>
          性别:
          <label>
            <input type="radio" v-model='obj.sex' value="男">
            <i></i>男
          </label>
          <label>
            <input type="radio" v-model='obj.sex' value="女">
            <i></i>女
          </label>

        </li>
        <li class='noBack'>
          年龄:
          <input type="number" placeholder="请填写患者真实年龄" v-model='obj.age'>
        </li>
        <li class='noBack'>
          手机号:
          <input type="text" placeholder="请填写患者手机号" v-model='obj.tele'>
        </li>
      </ul>
      <!-- <ul v-if="this.name=='clinic'">
        <li class='selectpatient' @click='selectpatient'>
          <img src="../../image/bg_touxiang@2x.png" width='43' height='43' alt="">
          <span>{{patientObj.name || "请选择患者"}}</span>
        </li>
      </ul> -->
      <ul>
        <li @click='toggle(1)'>
          <span>就诊时间</span>
          <span class='flex'>{{obj.time || '未选择'}}</span>
        </li>
        <!-- <li @click='isDuration=true'>
          <span>类型</span>
          <i class='flex'>{{obj.type||'未选择'}}</i>
        </li> -->
        <li @click='selectProject'>
          <span>项目</span>
          <span class='flex'>{{obj.project || '未指定项目'}}</span>
        </li>
        <li class='noBack remarks'>
          <span>备注:</span>
          <textarea placeholder="请输入备注" v-model='obj.remarks'></textarea>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        id: '', //预约记录id
        status: '医生新增预约', //编辑预约 || 新增预约
        name:'',//当前身份
        showMarks: false,
        kindlist: [],
        kindIndex: '',
        obj: {
          //   pid: '',
          doctorid: '',
          time: '', //就诊时间
          //   type: '', //就诊时长
          project: '', //选择项目
          remarks: '', //备注 
          name: '', //患者姓名
          sex: '', //性别
          tele: '', //手机号
          age: '', //年龄
        },

        patientObj: {
          name: ''
        }, //患者对象
        isTime: false, //是否显示时间选择器
        valuestime: '', //就诊时间选择但未确定时的选项
        slotsTime: [{
            flex: 2,
            values: function () {
              const date1 = new Date(); //获取当前时间
              const dayArr = []; //定义一个数组存储所以时间
              for (var i = 0; i < 6; i++) {
                const date2 = new Date(date1);
                date2.setDate(date1.getDate() + i);
                const month = date2.getMonth() + 1;
                const day = date2.getDate();
                var month1, day1;
                if (month < 10) {
                  month1 = '0' + month
                } else {
                  month1 = month
                }
                if (day < 10) {
                  day1 = '0' + day
                } else {
                  day1 = day
                }
                const times = date2.getFullYear() + "-" + month1 + "-" + day1;
                dayArr.push(times); //把未来几天的时间放到数组里
              }
              return dayArr;
            }(),
            className: 'slot1',
            textAlign: 'center',
            defaultIndex: 0,
            value: function () {
              const date1 = new Date(); //获取当前时间
              const date2 = new Date(date1);
              date2.setDate(date1.getDate());
              const month = date2.getMonth() + 1;
              const day = date2.getDate();
              var month1, day1;
              if (month < 10) {
                month1 = '0' + month
              } else {
                month1 = month
              }
              if (day < 10) {
                day1 = '0' + day
              } else {
                day1 = day
              }
              const times = date2.getFullYear() + "-" + month1 + "-" + day1;



              return times;
            }(),
          },
          {
            flex: 1,
            values: function () {
              const hourArr = [];
              for (var i = 0; i < 24; i++) {
                if (i < 10) {
                  hourArr.push('0' + i + ":00");
                } else {
                  hourArr.push(i + ":00");
                }

              }
              return hourArr;
            }(),
            className: 'slot2',
            textAlign: 'center',
            defaultIndex: function () {
              const date1 = new Date(); //获取当前时间
              const date2 = new Date(date1);
              date2.setHours(date1.getHours() + 4);
              const times = date2.getHours();
              return times;
            }(),
            value: function () {
              const date1 = new Date(); //获取当前时间
              const date2 = new Date(date1);
              date2.setHours(date1.getHours() + 4);
              const times = date2.getHours() + ":" + "00";
              return times;
            }(),

          },
        ],
        isDuration: false, //是否显示时长选择器
        values: '', //就诊时长选择但未确定时的选项
        slots: [{
          values: ['初诊', '复诊'],
          className: 'slot1',
          textAlign: 'right',
          defaultIndex: 0,
          value: "初诊"
        }, ],
        isOpenA: true,
        isOpenB: false,
      }
    },
    watch: {
      obj: {
        handler(val, oldVal) {
          if (val.pid) {
            this.getPatient(val.pid);
          }
        },
        deep: true
      }
    },
    methods: {
      // 根据pid获取患者详情
      getPatient(pid) {
        // var pid = this.$route.query.pid;
        this.$api.get(this.$api.baseURLSchool, "select_cid/patient/" + pid, {}, r => {
          if (r.data.ret == 1) {
            this.patientObj = r.data.info;
          }
        }, err => {
          console.log(err);
        })
      },
      //根据不同入口返回上一级
      goBack() {
        const from = this.$route.query.from;
        const pid = this.$route.query.pid;
        if (from) {
          if (pid) {
            this.$router.push({
              name: from,
              query: {
                id: pid
              }
            });
          } else if (this.id) {
            this.$router.push({
              name: from,
              query: {
                id: this.id
              }
            });
          } else {
            this.$router.push({
              name: from
            });
          }
        }

      },
 //选择患者
 selectpatient() {
        const from0 = this.$route.query.from;
        if (from0) {
          this.$router.push({
            name: 'selectpatient',
            query: {
              from0: from0,
              from: 'addNewAppointment'
            }
          });
        }
      },
      //选择项目
      handleOpen(key, keyPath) {},
      handleClose(key, keyPath) {},
      selectProject() {
        this.showMarks = true;
        var name = '病历模板'
        this.$api.get(this.$api.baseURLSchool, "selecttreedata/view_join_medical_templates/?name=" + name, {}, r => {
          if (r.data.ret == 1) {
            var id = [];
            this.kindlist = r.data.info
          }
        }, err => {
          console.log(err);
        })
      },
      select1(id) {
        this.kindIndex = id;
      },
      sure() {
        this.$api.get(this.$api.baseURLSchool, "selectdata2/view_join_medical_templates?id=" + this.kindIndex, {},
          r => {
            if (r.data.ret == 1) {
              this.showMarks = false;
              this.obj.project = r.data.info[0].name
            }
          }, err => {
            console.log(err);
          })
      },
      // 控制日期选择器显示隐藏动画
      toggle(status) { //status 0隐藏 1显示
        if (status) {
          this.isTime = true;
          $(".datetime").addClass("up").removeClass("down");
        } else {
          $(".datetime").addClass("down").removeClass("up");
          this.isTime = false;
          setTimeout(function () {
            $(".datetime").removeClass("down");
          }, 700);
        }
      },
      //就诊时间
      onValuesChangeTime(picker, values) {
        this.valuestime = values.join(" ");
        const date = new Date();
        const currentDate = this.$utils.commentTime(date, 'yyyy-MM-dd hh:mm:ss');
        const diff = this.$utils.GetDateDiff(currentDate, this.valuestime, 'hour');
        // 必须至少提前三小时
        if (diff < 4) {
          const date2 = new Date(date);
          date2.setHours(date.getHours() + 4);

          const month = date2.getMonth() + 1;
          const day = date2.getDate();
          var month1, day1;
          if (month < 10) {
            month1 = '0' + month
          } else {
            month1 = month
          }
          if (day < 10) {
            day1 = '0' + day
          } else {
            day1 = day
          }
          const times = date2.getFullYear() + "-" + month1 + "-" + day1;
          picker.setSlotValue(0, times);
          const h = date2.getHours();
          var hours;
          if (h < 10) {
            hours = '0' + h;
          } else {
            hours = h;
          }
          const times2 = hours + ":" + "00";
          picker.setSlotValue(1, times2);
        }
        this.valuestime = values.join(" ");
      },
      //确定就诊时间
      sureTime() {
        this.obj.time = this.valuestime;
        this.toggle(0);
      },
      //选择完后
      init() {
         this.name=JSON.parse(localStorage.getItem('name') )
        if (this.$route.query.id) {
          this.status = "编辑预约";
          this.id = this.$route.query.id;
          this.$api.get(this.$api.baseURLSchool, "select_cid/appointment/" + this.id, {}, r => {
            // console.log(r);
            if (r.data.ret == 1) {
              this.obj = r.data.info;
            }
          }, err => {
            console.log(err);
          })
        } else if (this.$route.query.pid) {
          this.obj.pid = this.$route.query.pid;
        } else if (this.$route.query.project) {
          this.obj.project = this.$route.query.project.join();
        } else {
          this.pname = "";
          this.obj = {
            // pid: '',
            doctorid: '',
            name: '', //患者姓名
            sex: '', //性别
            age: '', //年龄
            tele: '', //手机号
            time: '', //就诊时间
            project: '', //选择项目
            remarks: '', //备注 
          };
        }

      },
      //保存预约
        //保存
        // save() {
        //   // 新建患者
        //   if (this.obj.name && this.obj.sex && this.obj.age && this.obj.tip && this.obj.remarks) {
    
        //     if (this.status == "add") {
        
        //     } else if (this.status == "edit") {
            
        //     }
        //   } else {
        //     this.$utils._toast("以上信息请填写完整");
        //   }
        // },
      save() {
        this.obj.doctorid = localStorage.getItem("loginMobile");
        if (!this.obj.name) {
          this.$utils._toast("请输入患者姓名");
          return false;
        } else if (!this.obj.sex) {
          this.$utils._toast("请选择患者性别");
          return false;
        } else if (!this.obj.age) {
          this.$utils._toast("请输入患者年龄");
          return false;
        } else if (!this.obj.tele) {
          this.$utils._toast("请输入患者手机号");
          return false;
        }
        // else if (this.obj.tele) {
        //   if (!(/^1[34578]\d{9}$/.test(this.obj.tele))) {
        //     this.$utils._toast("手机号码不合法");
        //     return false;
        //   }
        // }
        // else if (!this.obj.time) {
        //   this.$utils._toast("请选择就诊时间");
        //   return false;
        // } else if (!this.obj.project) {
        //   this.$utils._toast("请选择项目");
        //   return false;
        // }
        
        else {
          console.log(this.obj);
          if (this.status == "医生新增预约") {

            this.$api.post(this.$api.baseURLSchool, "updatedata/patient/add", this.obj, r => {
                console.log('***',r);
                
                if (r.data.ret == 1) {
                  this.$utils._toast("保存成功");
    
                }
              }, err => {
                console.log(err);
              })
            this.$api.post(this.$api.baseURLSchool, "updatedata/appointment/add", this.obj, r => {
              console.log(r);
              if (r.data.ret == 1) {
                this.$utils._toast("保存成功");
                setTimeout(() => {
                  this.goBack();
                }, 300);
              }
            }, err => {
              console.log(err);
            })
          } else if (this.status == "编辑预约") {
            this.$api.post(this.$api.baseURLSchool, "updatedata/patient/edit", this.obj, r => {
                if (r.data.ret == 1) {
                  this.$utils._toast("保存成功");
                  setTimeout(() => {
                    this.$router.back();
                  }, 300);
                }
              }, err => {
                console.log(err);
              })
            this.$api.post(this.$api.baseURLSchool, "updatedata/appointment/edit", this.obj, r => {
              console.log(r);
              if (r.data.ret == 1) {
                this.$utils._toast("保存成功");
                setTimeout(() => {
                  this.goBack();
                }, 300);
              }
            }, err => {
              console.log(err);
            })
          }
        }


      }
    },
    created() {},
    activated() {
      this.init();
    },
  }

</script>
<style lang="scss" scoped>
  .base li input {
    text-align: left !important;
  }

</style>
